package com.zigin.healthcard.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/*#################################################################*
# 说明:以下代码通过哲勤代码生成工具自动生成    
# 工具:GeneratorCode
# 作者:mgw1986                                                  
# 生成时间:2016-9-23 12:12:11                                               
##################################################################*/

/**
 * 控制器基类
 *
 * @author mgw1986
 * @version V1.0
 * @ClassName: BaseController
 * @date 2016-9-23 12:12:11
 */
public class BaseController {
    protected Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    protected HttpServletRequest request;
    @Autowired
    protected HttpServletResponse response;
    @Autowired
    protected HttpSession session;

    /**
     * 获取cookie的值
     *
     * @param name cookie名称
     * @return cookie的值
     */
    protected String getCookie(String name) {
        Cookie[] cookies = request.getCookies();
        if (null == cookies || cookies.length == 0) {
            return null;
        }
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(name)) {
                return cookie.getValue();
            }
        }
        return null;
    }

    /**
     * 编辑cookie，如果cookie不存在，则创建cookie
     *
     * @param name  cookie名称
     * @param value cookie值
     */
    protected void setCookie(String name, String value) {
        Cookie[] cookies = request.getCookies();
        if (null == cookies || cookies.length == 0) {
            Cookie cookie = new Cookie(name, value);
            cookie.setPath("/");
            response.addCookie(cookie);
            return;
        }
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(name)) {
                cookie.setValue(value);
                response.addCookie(cookie);
                return;
            }
        }
    }

    /**
     * 删除cookie
     *
     * @param name cookie名称
     */
    protected void deletCookie(String name) {
        Cookie[] cookies = request.getCookies();
        if (null == cookies || cookies.length == 0) {
            return;
        }
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(name)) {
                cookie.setValue(null);
                cookie.setMaxAge(0);
                response.addCookie(cookie);
                return;
            }
        }
    }

    /**
     * 添加session
     */
    protected void setSession(String key, Object value) {
        session.setAttribute(key, value);
    }

    /**
     * 获取session
     *
     * @param key session名
     * @return session对应的值
     */
    protected Object getSession(String key) {
        return session.getAttribute(key);
    }
}
